package com.qs.rocketmq.bt.mq.selector;

import com.qs.rocketmq.bt.mq.MqConstant;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MessageSelector;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 消息消费端：测试消息消费使用sql过滤
 *
 * @since 2022-07-18 22:58:47
 */
public class MsgConsumer {

    public static void main(String[] args) throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(MqConstant.CONSUMER_GROUP_NAME);
        consumer.setNamesrvAddr(MqConstant.MQ_NAME_SRV_ADDR);
        // 根据消息属性，使用sql过滤
        consumer.subscribe(MqConstant.TEST_TOPIC, MessageSelector.bySql("age between 0 and 3"));
//        consumer.subscribe(MqConstant.TEST_TOPIC, "*");
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                msgs.forEach(msg -> {
                    byte[] body = msg.getBody();
                    String msgContent = new String(body, 0, body.length, StandardCharsets.UTF_8);
                    System.out.println(Thread.currentThread().getName() + "，" + msgContent);
                });
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();
        System.out.println("consumer started。。。");
    }
}
